from django.utils.deprecation import MiddlewareMixin
from web import models

from django.shortcuts import render, redirect, HttpResponse
import datetime
from django.conf import settings


class Tracer:
    def __init__(self):
        self.user = None
        self.Price_Policy = None
        self.project = None


class auth_middleware(MiddlewareMixin):
    def process_request(self, request):
        user_id = request.session.get('user_id', 0)
        user_obj = models.user_info.objects.filter(pk=user_id).first()

        # 实例Tracer对象
        request.tracer = Tracer()
        request.tracer.user = user_obj

        # 登录认证
        # # 如果在白名单中通过
        if request.path_info in settings.WHITE_LIST:
            return
        # 不在里面,查看是否登录
        if not request.tracer.user:
            return redirect('login_code')

        # 价格策略的封装
        # 查询到当前id号最大的交易记录
        # 收费的交易记录
        transaction_obj = models.Transaction.objects.filter(user_info=user_obj, status=2).order_by('-id').first()

        # 免费的交易记录
        free_obj = models.Transaction.objects.filter(user_info=user_obj, status=2).order_by('id').first()
        # 进行判断，策略是否过期
        # 1. 是否有end_time 有购买，无免费版的
        if transaction_obj.end_time and transaction_obj.end_time < datetime.datetime.now():
            #  没有过期
            _price_policy = transaction_obj.price_policy
        else:
            # 过期或未购买用免费版的
            _price_policy = free_obj.price_policy
        # 封装
        request.tracer.Price_Policy = _price_policy

    def process_view(self, request, view, args, kwargs):
        # 判断是否以manage开头的，
        if not request.path_info.startswith('/manage/'):
            return
        # 判断是否为自己创建的
        project_id = kwargs.get('project_id')
        # print(project_id)
        project_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_obj:
            request.tracer.project = project_obj
            return
        # 判断是否为加入的
        project_join = models.ProjectUser.objects.filter(user=request.tracer.user, id=project_id).first()
        if project_join:
            request.tracer.project = project_join.project
            return
        # 都不是返回
        return redirect('project')
